<template>
    <div>
        <!-- 数据筛选区域 -->
        <el-form :model="page" :inline="true" class="filter-form">
            <el-form-item label="编号" prop="id" style="width: 200px;">
                <el-input v-model="page.entrepotCode" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="仓库名称" prop="warehouseName" style="width: 200px;">
                <el-input v-model="page.entrepotName" />
            </el-form-item>
            <el-form-item label="部门" style="width: 200px;">
                <el-select v-model="page.entrepotDept" placeholder="请选择">
                    <el-option label="技术部" value="技术部" />
                    <el-option label="销售部" value="销售部" />
                </el-select>
            </el-form-item>
            <el-form-item label="仓库类型" style="width: 200px;">
                <el-select v-model="page.entrepotType" placeholder="请选择">
                    <el-option label="一号仓库" value="一号仓库" />
                    <el-option label="二号仓库" value="二号仓库" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="query()">查询</el-button>
                <el-button>重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 数据列表区域 -->
        <div class="action-buttons">

            <el-button type="success" @click="tk.IsAdd = true" round>新增</el-button>
            <el-button type="warning" @click="tk.IsUpdate = true" round>编辑</el-button>

            <el-button type="danger">删除</el-button>
            <el-button type="success" @click="commandShow">导出</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="100" />
            <el-table-column prop="entrepotCode" label="仓库编号" />
            <el-table-column prop="entrepotName" label="仓库名称" />
            <el-table-column prop="entrepotTime" label="租赁时间" />
            <el-table-column prop="entrepotType" label="仓库类型" />
            <el-table-column prop="entrepotDept" label="所属部门" />
            <el-table-column prop="entrepotEffect" label="所属部门" />
            <el-table-column prop="entrepotAdd" label="地址" />
            <el-table-column prop="entrepotArea" label="面积" />
            <el-table-column prop="entrepotPerson" label="联系人" />
            <el-table-column prop="entrepotPheon" label="电话" />
            <el-table-column label="操作">
                <template #default="scoped">
                    <el-button type="danger" @click="del(scoped.row.entrepotId)" size="small">删除</el-button>
                    <el-button type="text" size="small" @click="upd(scoped.row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 弹框新增 -->
        <el-dialog v-model="tk.IsAdd" title="仓库新增" width="500" draggable>
            <template #footer>
                <div class="dialog-footer">
                    <el-form-item label="单位编号">
                        <el-input v-model="bd.entrepotCode" disabled />
                    </el-form-item>

                    <el-form-item label="部门名称">
                        <el-select v-model="bd.entrepotDept">
                            <el-option label="技术部" value="技术部" />
                            <el-option label="销售部" value="销售部" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="仓库名称">
                        <el-input v-model="bd.entrepotName" />
                    </el-form-item>

                    <el-form-item label="仓库类型">
                        <el-select v-model="bd.entrepotType">
                            <el-option label="一号仓库" value="一号仓库" />
                            <el-option label="二号仓库" value="二号仓库" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="作用">
                        <el-input v-model="bd.entrepotEffect" />
                    </el-form-item>

                    <el-form-item label="租赁时间">
                        <el-input v-model="bd.entrepotTime" :disabled="true" />
                    </el-form-item>

                    <el-form-item label="面积">
                        <el-input v-model="bd.entrepotArea" />
                    </el-form-item>

                    <el-form-item label="地址">
                        <el-input v-model="bd.entrepotAdd" />
                    </el-form-item>

                    <el-form-item label="联系人">
                        <el-input v-model="bd.entrepotPerson" />
                    </el-form-item>

                    <el-form-item label="电话">
                        <el-input v-model="bd.entrepotPheon" />
                    </el-form-item>

                    <el-button @click="tk.IsAdd = false">取消</el-button>
                    <el-button type="primary" @click="Save">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 弹框修改 -->
        <el-dialog v-model="tk.IsUpdate" title="仓库修改" width="500" draggable>
            <template #footer>
                <div class="dialog-footer">
                    <el-form-item label="单位编号">
                        <el-input v-model="bd.entrepotCode" disabled />
                    </el-form-item>

                    <el-form-item label="部门名称">
                        <el-select v-model="bd.entrepotDept">
                            <el-option label="技术部" value="技术部" />
                            <el-option label="销售部" value="销售部" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="仓库名称">
                        <el-input v-model="bd.entrepotName" />
                    </el-form-item>

                    <el-form-item label="仓库类型">
                        <el-select v-model="bd.entrepotType">
                            <el-option label="一号仓库" value="一号仓库" />
                            <el-option label="二号仓库" value="二号仓库" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="作用">
                        <el-input v-model="bd.entrepotEffect" />
                    </el-form-item>

                    <el-form-item label="租赁时间">
                        <el-input v-model="bd.entrepotTime" :disabled="true" />
                    </el-form-item>

                    <el-form-item label="面积">
                        <el-input v-model="bd.entrepotArea" />
                    </el-form-item>

                    <el-form-item label="地址">
                        <el-input v-model="bd.entrepotAdd" />
                    </el-form-item>

                    <el-form-item label="联系人">
                        <el-input v-model="bd.entrepotPerson" />
                    </el-form-item>

                    <el-form-item label="电话">
                        <el-input v-model="bd.entrepotPheon" />
                    </el-form-item>

                    <el-button @click="tk.IsUpdate = false">取消</el-button>
                    <el-button type="primary" @click="update">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 分页组件 -->
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="page.TotalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { KongaUrl } from '@/axios/axiosHelp';

// 分页
const page = reactive({
    PageIndex: 1,
    PageSize: 15,
    TotalCount: 0,
    PageCount: 0,
    "entrepotCode": "",
    "entrepotName": "",
    "entrepotDept": "",
    "entrepotType": "",
});

const bd = reactive({
    entrepotId: 0,
    entrepotCode: "",
    entrepotName: "",
    entrepotDept: "",
    entrepotType: "",
    entrepotEffect: "",
    entrepotTime: "2025-04-12",
    entrepotArea: "",
    entrepotAdd: "",
    entrepotPerson: "",
    entrepotPheon: "",
    entrepotMapp: "123",
});

// 弹框
const tk = reactive({
    // 新增
    IsAdd: false,
    // 编辑
    IsUpdate: false,
});
const tableData = ref([])

//分页查询
const query = () => {
    KongaUrl.get("/wangxin/api/Entrepot/GetEntrepotQuery", {
        params: {
            PageIndex: page.PageIndex,
            PageSize: page.PageSize,
            entrepotCode: page.entrepotCode,
            entrepotName: page.entrepotName,
            entrepotDept: page.entrepotDept,
            entrepotType: page.entrepotType,
        }
    }).then(res => {
        tableData.value = res.data.list;
        page.TotalCount = res.data.totalCount;
        page.PageCount = res.data.pageCount;
    });
}
// 单位新增
const Save = () => {
    console.log(bd);
    KongaUrl.post("/wangcong1/api/Entrepot/AddEntrepot", bd).then(res => {
        console.log(res.data);
        if (res.data.code == 200) {
            ElMessage.success("添加成功");
            tk.IsAdd = false;
            query();
        }
        else {
            ElMessage.success("添加成功");
            tk.IsAdd = false;
            query()
        }
    });
};

// 单删除
const del = (entrepotId: any) => {
    ElMessageBox.confirm("是否确认删除?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
    }).then(() => {
        KongaUrl.delete("wangcong1/api/Entrepot/DeleteEntrepot", {
            params: {
                EntrepotId: entrepotId
            }
        }).then((res) => {
            if (res.data.code == 500) {
                ElMessage.success("删除成功");
                query();
            } else {
                ElMessage.error("删除失败");
            }
        });
    });
};

// 反填
const upd = (row: any) => {
    bd.entrepotId = row.entrepotId;
    bd.entrepotCode = row.entrepotCode;
    bd.entrepotName = row.entrepotName;
    bd.entrepotDept = row.entrepotDept;
    bd.entrepotType = row.entrepotType;
    bd.entrepotEffect = row.entrepotEffect;
    bd.entrepotTime = row.entrepotTime;
    bd.entrepotArea = row.entrepotArea;
    bd.entrepotAdd = row.entrepotAdd;
    bd.entrepotPerson = row.entrepotPerson;
    bd.entrepotPheon = row.entrepotPheon;
    bd.entrepotMapp = row.entrepotMapp;
    tk.IsUpdate = true;
};

// 修改
const update = (row: any) => {
    KongaUrl.post("/wangcong1/api/Entrepot/UpdEntrepot", bd)
        .then(res => {
            if (res.data.code == 300) {
                ElMessage.success("修改成功");
                tk.IsUpdate = false;
                query();
            }
            else {
                ElMessage.success("修改成功");
                tk.IsUpdate = false;
                query();
            }
        });
};

//导出
const commandShow = async () => {
    const ids = selectedRows.value.map(row => row.entrepotId);
    if (!ids.length) {
        ElMessage.error('请选择需要导出的商品');
        return;
    }

    try {
        // 构建参数
        const queryParams = ids.map(id => `entrepotId=${id}`).join('&');
        const url = `/wangcong/Entrepot/ExportOrderList?${queryParams}`;

        // 发送请求获取二进制流
        const response = await axios.get(url, {
            responseType: 'arraybuffer', // 明确响应类型为二进制
        });

        // 解析文件名（从响应头获取）
        const contentDisposition = response.headers['content-disposition'];
        const fileName = contentDisposition?.match(/filename="?([^"]+)"/)?.[1] || '仓库管理列表.xlsx';

        // 生成Blob并触发下载
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = fileName;
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(downloadUrl);

    } catch (error) {
        console.error('导出错误:', error);
        ElMessage.error(`导出失败: ${error.message}`);
    }
};

const generateTwelveDigitNumber = () => {
    const characters = "0123456789";
    let result = "";
    for (let i = 0; i < 12; i++) {
        // 生成12位数字
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
};

onMounted(() => {
    query();
    bd.entrepotCode = generateTwelveDigitNumber();
});
// 多选按钮存入数据
const selectedRows = ref<any[]>([]); // 存储选中行的数据

// 多选事件回调
const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows; // 将选中的行数据保存到变量中
};

// 分页
const handleSizeChange = (index: any) => {
    page.PageSize = index;
    query();
};

const handleCurrentChange = (index: any) => {
    page.PageIndex = index;
    query();
};

</script>

<style scoped>
.filter-form {
    margin-bottom: 15px;
}
</style>